package cn.itcalvin.stat.exam.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.itcalvin.stat.exam.pojo.req.ReqSearch;
import cn.itcalvin.stat.exam.pojo.resp.RespStat;
import cn.itcalvin.stat.exam.pojo.resp.RespStatDetails;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;

import cn.itcalvin.stat.exam.mapper.StatUserMapper;
import cn.itcalvin.stat.exam.domain.StatUser;
import cn.itcalvin.stat.exam.service.StatUserService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StatUserServiceImpl implements StatUserService{

    @Resource
    StatUserMapper statUserMapper;

    @Override
    public List<RespStat> search(ReqSearch reqSearch) {
        return statUserMapper.search(reqSearch.getStartDate(),
                reqSearch.getEndDate());
    }

    @Override
    @Cacheable(value = "searchDetailsCache", key = "#reqSearch.startDate+#reqSearch.endDate+#reqSearch.orgIds+#reqSearch.keyword")
    public List<RespStatDetails> searchDetails(ReqSearch reqSearch) {
        List<RespStatDetails>  list1= statUserMapper.searchDetails(reqSearch.getStartDate(),
                reqSearch.getEndDate()
        ,reqSearch.getOrgIds(),reqSearch.getKeyword());
        List<RespStatDetails>  list2= statUserMapper.searchZsDetails(reqSearch.getStartDate(),
                DateUtil.offsetDay(DateUtil.parseDate(reqSearch.getEndDate()),1).toString("yyyy-MM-dd")
                ,reqSearch.getOrgIds(),reqSearch.getKeyword());
        if(list2==null||list2.size()==0){
            return list1;
        }
        list1.forEach(x->{
            final Optional<RespStatDetails> first = list2.stream().filter(y -> y.getUserId().equals(x.getUserId())).findFirst();
            first.ifPresent(respStatDetails -> x.setZsKs(respStatDetails.getZsKs()));
        });
        return list1;
    }
}
